import Setting from '@/setting';
import websocketfun from './chatwebsocket/websocketfun';

let WebSocketObj = null;
let websocketUrl = null; // 默认地址
var lockReconnect = false; // 避免重复连接
let timeoutObj = null;// 心跳定时obj【最后一次发送非心跳消息之后定时发送】
var tt;
let linkTimes = 0; // 连接的次数 4次就提示连接失败
import base64 from '@/libs/base64.js';
import util from '@/libs/util';
// 实例websocket
function createWebSocket() {
    let token = util.cookies.get('token');
    // console.log('token', token);
    // let url = `${Setting.websocketUrl}?access_token=${token}`;
    // websocketUrl = url; // 默认地址
    websocketUrl = `${Setting.websocketUrl}?access_token=${token}`
    WebSocketObj = new WebSocket(websocketUrl);
    linkTimes++;
    initWebSocket();


    let wechatId = localStorage.getItem('currentConversationId');
    if (wechatId) {
        setTimeout(() => {
            // let wechatInfo = localStorage.getItem('wechatInfo');
            // console.log(localStorage.getItem('menus'),'menus');
            // console.log('执行建立通道', wechatInfo);
            let msg = {
                Id: 1010,
                AccessToken: '',
                MsgType: 'DeviceAuthReq',
                Content: {
                    AuthType: 2,
                    Credential: base64.b64EncodeUnicode(wechatId)
                }
            };
            sendSock(msg);
        }, 1000);
    }
}

// 初始化事件函数
function initWebSocket() {
    // console.log('我开始了');
    WebSocketObj.onclose = () => {
        reconnect();
    };
    WebSocketObj.onerror = e => {
        if (linkTimes >= 4) {
            console.log('重连连续失败3次，退出登陆');
        }
    };

    WebSocketObj.onopen = () => {
        // websocket打开
        // 心跳检测重置
        heartCheck.start();
    };

    WebSocketObj.onmessage = event => {
        // 拿到任何消息都说明当前连接是正常的
        handleMsg(event);
    };
}

/**
 * 尝试重连
 */
function reconnect() {
    // 如果账号在别的地方登陆 || 或者token过期就不再重连了 || 主动退出 都不再重连
    if (lockReconnect) return;
    lockReconnect = true;

    tt && clearTimeout(tt);
    tt = setTimeout(function () {
        // 重置链接次数
        linkTimes = 0;
        // 创建ws链接
        createWebSocket(websocketUrl);
        // 取消重连锁
        lockReconnect = false;
    }, 5000);
}

// 心跳检测
var heartCheck = {
    timeout: 15000, // 心跳检测时长
    // timeoutObj: null, //  定时变量
    // serverTimeoutObj: null, // 服务器超时
    start: function () {
        // console.log('WebSocketObj.readyState', WebSocketObj.readyState);
        if (WebSocketObj.readyState === 1) {
            // 重置心跳
            timeoutObj && clearInterval(timeoutObj);
            timeoutObj = setInterval(function () {
                // 这里发送一个心跳，后端收到后，返回一个心跳消息，
                let msg = {
                    Id: 1001,
                    MsgType: 'HeartBeatReq',
                    AccessToken: ''
                };
                sendSock(msg);
            }, this.timeout);
        }
    }
};

// 数据接收处理
function handleMsg(e) {
    let msg = JSON.parse(e.data);
    let msgType = msg.msgType;
    switch (msgType) {
        // websocket建立连接后登录处理
        case 'DeviceAuthRsp':
            websocketfun.deviceAuthRspHandle(msg);
            break;
        // 会话列表
        case 'ConversationPushNotice':
            websocketfun.conversationPushNoticeHandle(msg);
            break;
        // 获取历史消息
        case 'QueryHistoryMessageResp':
            websocketfun.QueryHistoryMessageRespHandle(msg);
            break;
        // 好友发来消息
        case 'FriendTalkNotice':
            websocketfun.FriendTalkNoticeHandle(msg);
            break;
        // 我发送消息给好友
        case 'TalkToFriendTaskResultNotice':
            // console.log('发送成功');
            websocketfun.TalkToFriendTaskResultNoticeHandle(msg);
            break;
        // 手机消息已读通知
        case 'PostMessageReadNotice':
            websocketfun.postMessageReadNoticeHandle(msg);
            break;
        // 查看消息详情
        case 'RequestTalkDetailTaskResultNotice':
            websocketfun.RequestTalkDetailTaskResultNoticeHandle(msg);
            break;
        // 下线通知
        case 'WeChatOfflineNotice':
            websocketfun.WeChatOfflineNoticeHandle(msg);
            break;
        // 上线通知
        case 'WeChatOnlineNotice':
            websocketfun.WeChatOnlineNoticeHandle(msg);
            break;
        // 置顶or取消通知
        case 'TaskResultNotice':
            websocketfun.TaskResultNoticeHandle(msg);
            break;
        case 'Error':
            let errMessage = JSON.parse(msg.message).ErrorMsg;
            if (errMessage === '账号密码错误') {
                // localStorage.removeItem('wsInfo');
                // store.dispatch('websocket/account/SetRelogin', 'false');
                // store.dispatch('websocket/account/SetUser', {}); // 设置用户信息
                // store.dispatch('websocket/account/SetToken', ''); // 设置token信息
                // store.dispatch('websocket/account/SetLogin', false); // 修改登录状态
            } else if (JSON.parse(errMessage).errorMsg === '对方不在线') {
                // let wechatsInfos = JSON.parse(localStorage.getItem('wechatsInfos'))
                // for (let item of wechatsInfos) {
                //     if (JSON.parse(errMessage).weChatId == item.WeChatId) {
                //         Message.error({ content: `微信昵称：${item.WeChatname}不在线，请检查你的客服微信是否正常登录。`, duration: 3 });
                //     }
                // }
            } else {
                // Message.error({ content: `${errMessage}`, duration: 3 });
            }
            break;
        // 服务端返回
        case 'MsgReceivedAck':
            switch (msg.refMsgId) {
                case 1001:
                    break;
                default:
                    // Message.success("操作成功");
                    break;
            }
            break;
        default:
            break;
    }
}

// 发送指令
function sendSock(agentData) {
    // 若是ws开启状态
    if (WebSocketObj && WebSocketObj.readyState === WebSocketObj.OPEN) {
        // 发送指令
        WebSocketObj.send(JSON.stringify(agentData));
        // 心跳发送倒计时
        if (agentData.MsgType !== 'HeartBeatReq') {
            heartCheck.start();
        }
    } else if (
        WebSocketObj &&
        WebSocketObj.readyState === WebSocketObj.CONNECTING
    ) {
        // 若是 正在开启状态，则等待1s后重新调用
        setTimeout(() => {
            sendSock(agentData);
        }, 1000);
    }
}

// 关闭websocket
function closeWebsocket() {
    // console.log('我关了');
    if (WebSocketObj && WebSocketObj.readyState === WebSocketObj.OPEN) {
        // console.log('我关了2', timeoutObj);
        lockReconnect = true;
        WebSocketObj.close();
        timeoutObj && clearInterval(timeoutObj);
    }
}

export { sendSock, createWebSocket, closeWebsocket };
